import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { NzModalService, NzNotificationService, NzMessageService } from 'ng-zorro-antd';
import { EndMatchComponent } from '../end-match/end-match.component';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styles: []
})
export class ListComponent implements OnInit {
  dataSet = [];
  loading = false;

  constructor(private http: HttpClient, private modalService: NzModalService, private notification: NzMessageService) {


  }

  ngOnInit(): void {
    for (let i = 0; i < 100; i++) {
      this.dataSet.push({
        name: `Edward King ${i}`,
        age: 32,
        address: `London, Park Lane no. ${i}`
      });
    }

    this.getData();
  }

  getData() {
    this.loading = true;
    this.http.get('/sjb/matchs/all').subscribe(res => {
      this.loading = false;
      if (res && !res.hasOwnProperty('error') && Array.isArray(res)) {
        this.dataSet = res;
      }
    }, err => {
      this.loading = false;
      this.notification.error('错误! ' + err);
    });
  }

  endMatch(match): void {
    const modal = this.modalService.create({
      nzTitle: '请填写比赛结果',
      nzContent: EndMatchComponent,
      // nzComponentParams: {
      //   title: 'title in component',
      //   subtitle: 'component sub title，will be changed after 2 sec'
      // },
      nzFooter: [{
        label: '确认结束',
        onClick: (componentInstance) => {
          // componentInstance.title = 'title in inner component is changed';
          if (componentInstance.valid()) {
            modal.destroy();
            this.loading = true;
            console.log(componentInstance.getValue());
            this.http.post(`/sjb/match/${match._id}/final`, {
              end: true,
              ...componentInstance.getValue()
            }).subscribe(() => {
              this.loading = false;
              this.notification.success(
                '更新比赛状态成功！'
              );
              this.getData();
            }, (err) => {
              this.loading = false;
              this.notification.error(
                '结束比赛失败：' + err
              );
            });
          }
        }
      }]
    });

    // modal.afterOpen.subscribe(() => console.log('[afterOpen] emitted!'));

    // // Return a result when closed
    // modal.afterClose.subscribe((result) => console.log('[afterClose] The result is:', result));

    // delay until modal instance created
    // window.setTimeout(() => {
    //   const instance = modal.getContentComponent();
    //   // instance.subtitle = 'sub title is changed';
    // }, 2000);
  }
}
